﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace RCREEE.Desktop.UserControls
{
    public partial class ucSiteMapHandler : UserControl
    {
        public ucSiteMapHandler()
        {
            InitializeComponent();
        }

        private void ucSiteMapHandler_Load(object sender, EventArgs e)
        {
            command.Connection = connection;
            adapter.SelectCommand = command;
            BuildTree();
        }

        DataTable dtResults = new DataTable();
        SqlConnection connection = new SqlConnection("Data source=minamilad.db.9080910.hostedresource.com; Initial Catalog=minamilad; User ID=minamilad; Password=Mina@321;");
        SqlCommand command = new SqlCommand();
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataSet dsResults = new DataSet();

        private void BuildTree()
        {


          
            

            try
            {


                command.CommandText = @"
                                    SELECT  SiteMapNodeID, 
                                            Name, 
                                            Url, 
                                            ParentSiteMapNodeID 
                                    FROM SiteMapNodes inner join itemdetails 
                                    ON TitleId = ItemDetails.ItemId where LanguageCode = 1033 Order By Level";

               

               



                adapter.Fill(dtResults);

               
                try
                {


                    List<NodeSimulator> TreeSimulator = new List<NodeSimulator>();

                    DataRow drFirstNode = dtResults.Select("ParentSiteMapNodeId is NULL")[0];

                    RecAddNode(Convert.ToInt32(drFirstNode["SiteMapNodeId"]));

                    treeView2.Nodes.Add((TreeNode)treeView1.Nodes[0].Clone());

                }
                catch (Exception exc)
                {

                }
            }
            catch { }



        }

        public void RecAddNode(int NodeId)
        {
            try
            {
                DataRow drNode = dtResults.Select("SiteMapNodeId = " + NodeId.ToString())[0];

                TreeNode node = new TreeNode(drNode["Name"].ToString());
                node.Name = NodeId.ToString();

                DataRow drParent;

                if (drNode["ParentSiteMapNodeId"] != DBNull.Value)
                {


                    TreeNode parent = GetNode(treeView1.Nodes[0], drNode["ParentSiteMapNodeId"].ToString());
                    parent.Nodes.Add(node);

                }
                else
                {
                    treeView1.Nodes.Add(node);
                   
                }

                DataRow[] drNodeChildren = dtResults.Select("ParentSiteMapNodeId = " + NodeId.ToString());

                for (int i = 0; i < drNodeChildren.Length; i++)
                {
                    int childSiteMapNodeId = 0;

                    if (Int32.TryParse(drNodeChildren[i]["SiteMapNodeId"].ToString(), out childSiteMapNodeId))
                        RecAddNode(childSiteMapNodeId);
                }

            }
            catch (Exception exp)
            { 
            
            }

        }

        public TreeNode GetNode(TreeNode node, string Key)
        {
            if (node.Name == Key)
                return node;
            else if (node.Nodes.ContainsKey(Key))
                return node.Nodes[Key];
            else
            {
                for (int i = 0; i < node.Nodes.Count; i++)
                {
                    return GetNode(node.Nodes[i], Key);
                }
            }

            return null;
        }

        public Node GetNode(int SiteMapNodeId)
        {
            Node n = new Node();

            command.CommandText = @"
select * from SiteMapNodes WHERE SiteMapNodeId = " + SiteMapNodeId.ToString() + @"

declare @TitleId int
set @TitleId = ( SELECT TitleId FROM SiteMapNodes WHERE SiteMapNodeId = "+ SiteMapNodeId.ToString() +@" )

select * from ItemDetails where ItemId = @TitleId

declare @EntityId int
set @EntityId = ( SELECT EntityId FROM SiteMapNodes WHERE SiteMapNodeId = "+ SiteMapNodeId.ToString() +@" )

select * from ItemDetails WHERE ItemId = @EntityId
";


            dsResults = new DataSet();

            adapter.Fill(dsResults);

            DataRow drMain = dsResults.Tables[0].Rows[0];
           
            n.SiteMapNodeId = SiteMapNodeId;

            n.Url = drMain["Url"].ToString();

            n.Level = Convert.ToInt32(drMain["Level"]);

            if(drMain["ParentSiteMapNodeId"] != DBNull.Value)
            n.ParentNodeKey = Convert.ToInt32(drMain["ParentSiteMapNodeId"]);

            n.Title = GetMultiLingualItem(1);

            if(drMain["EntityId"] != DBNull.Value)
             n.Entity = GetMultiLingualItem(2);

            return n;
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            int nodeId = Convert.ToInt32(treeView1.SelectedNode.Name);

            Node tempN = GetNode(nodeId);

            txtSiteMapNodeId.Text = tempN.SiteMapNodeId.ToString();

            txtEntityEnglishName.Text = tempN.Entity.EnglishName;
            txtEntityArabicName.Text = tempN.Entity.ArabicName;
            txtEntityFrenchName.Text = tempN.Entity.FrenchName;

            txtTitleEnglish.Text = tempN.Title.EnglishName;
            txtTitleArabic.Text = tempN.Title.ArabicName;
            txtTitleFrench.Text = tempN.Title.FrenchName;

            txtUrl.Text = tempN.Url;

            txtLevel.Text = tempN.Level.ToString();

            if (tempN.ParentNodeKey != 0)
                treeView2.SelectedNode = GetNode(treeView2.Nodes[0], tempN.ParentNodeKey.ToString());
            treeView2.Refresh();
        }


        private MultilingualItem GetMultiLingualItem(int TableNumber)
        {
            MultilingualItem Item = new MultilingualItem();
            Item.ArabicName = dsResults.Tables[TableNumber].Select("LanguageCode = 1025")[0]["Name"].ToString();
            Item.EnglishName = dsResults.Tables[TableNumber].Select("LanguageCode = 1033")[0]["Name"].ToString();
            Item.FrenchName = dsResults.Tables[TableNumber].Select("LanguageCode = 1036")[0]["Name"].ToString();

            return Item;
        }

        private void btnNewNode_Click(object sender, EventArgs e)
        {
            treeView1.SelectedNode = null;

            txtSiteMapNodeId.Text = "";

            txtEntityEnglishName.Text = "";
            txtEntityArabicName.Text = "";
            txtEntityFrenchName.Text = "";

            txtTitleEnglish.Text =  "";
            txtTitleArabic.Text = "";
            txtTitleFrench.Text = "";

            txtUrl.Text = "";

            txtLevel.Text = "";


            treeView2.SelectedNode = null;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Node newNode = new Node();

            MultilingualItem entity = new MultilingualItem();
            entity.EnglishName = txtEntityEnglishName.Text;
            entity.ArabicName = txtEntityArabicName.Text;
            entity.FrenchName = txtEntityFrenchName.Text;

            MultilingualItem title = new MultilingualItem();
            title.EnglishName = txtTitleEnglish.Text;
            title.ArabicName = txtTitleArabic.Text;
            title.FrenchName = txtTitleFrench.Text;

            newNode.ParentNodeKey = Convert.ToInt32(treeView2.SelectedNode.Name);

            newNode.Level = Convert.ToInt32(txtLevel.Text);
        }
    }



    public class NodeSimulator
    {
        public int SiteMapNodeId;
        public List<NodeSimulator> Children;
    }

    public class Node
    {
        public int SiteMapNodeId;

        public MultilingualItem Title;
        public MultilingualItem Entity;

        public string Url;

        public int Level;

        public int ParentNodeKey;

        public Node()
        {
            try
            {

            }
            catch
            { 
            
            }
        }
    }

    public struct MultilingualItem
    {
        public string EnglishName;
        public string ArabicName;
        public string FrenchName;
    }



}
